package postgres

import (
	"context"
	"quipus/internal/database/model"

	_ "github.com/jackc/pgx/v5/stdlib"
	_ "github.com/joho/godotenv/autoload"
)

func (p *PGDB) UpsertSystemSetting(ctx context.Context, upsert *model.SystemSetting) error {
	p.query()
	qdo := q.WithContext(ctx)
	err := qdo.SystemSetting.Save(upsert)
	if err != nil {
		return err
	}

	return nil
}

func (p *PGDB) ListSystemSettings(ctx context.Context, settingKey string) ([]*model.SystemSetting, error) {
	p.query()
	qdo := q.WithContext(ctx)
	systemSetting := qdo.SystemSetting
	if len(settingKey) > 0 {
		systemSetting = systemSetting.Where(q.SystemSetting.Name.Eq(settingKey))
	}
	return systemSetting.Find()
}

func (p *PGDB) DeleteSystemSettings(ctx context.Context, settingKey string) error {
	p.query()
	qdo := q.WithContext(ctx)
	systemSetting := qdo.SystemSetting
	_, err := systemSetting.Where(q.SystemSetting.Name.Eq(settingKey)).Delete()

	if err != nil {
		return err
	}

	return nil
}
